package com.tulele.vtool.handler;

import com.google.common.collect.Maps;
import com.tulele.vtool.model.HeadBgImgInfo;
import com.tulele.vtool.model.PlatformSysInfo;
import com.tulele.vtool.model.UserInfo;
import com.tulele.vtool.model.reqEntity.UploadUserAvatarImgReqBean;
import com.tulele.vtool.model.reqEntity.UploadWxUserQrCodeImgReqBean;
import com.tulele.vtool.model.respEntity.RespData;
import com.tulele.vtool.model.respEntity.ReturnCode;
import com.tulele.vtool.service.HeadBgImgInfoService;
import com.tulele.vtool.service.IUserInfoService;
import com.tulele.vtool.service.SysGzhService;
import com.tulele.vtool.utils.*;
import com.tulele.vtool.wechat.service.WeixinService;
import com.tulele.vtool.wechat.service.WeixinServiceDL;
import com.tulele.vtool.wechat.service.WeixinServiceMap;
import com.tulele.vtool.wechat.service.WeixinServiceNew;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.*;

@Slf4j
@RestController
public class HeadBgImgInfoHandler {

    @Autowired
    private HeadBgImgInfoService headBgImgInfoService;

//    @Autowired
//    private WeixinService weixinService;

//    @Autowired
//    private ObjectFactory<WeixinServiceDL> objectFactory;

    @Autowired
    private IUserInfoService userInfoService;

    @Autowired
    private SysGzhService sysGzhService;

//    @Value("${wxShareImgPath}")
//    private String wxShareImgPath;
//
//    @Value("${spring.profiles.active}")
//    private String springProfilesActive;

    /**
     * 上传头像
     * 20200513 yl
     * @param userId
     * @param
     * @return
     * @throws IOException
     */
    @RequestMapping(value="/uploadHeadBgImg", method = RequestMethod.POST)
    public RespData uploadHeadBgImg(@RequestHeader("userId") String userId,@RequestHeader("identifying") String springProfilesActive, @RequestBody UploadUserAvatarImgReqBean uploadUserAvatarImgReqBean){
        if (uploadUserAvatarImgReqBean  == null || StringUtils.isBlank(uploadUserAvatarImgReqBean.getMediaId())) {
            RespData respData = new RespData();
            respData.setCode(ReturnCode.CLIENT_ERROR);
            respData.setMsg("参数异常");
            return respData;
        }
        String headBgImgUrl = null;
        String mediaId = uploadUserAvatarImgReqBean.getMediaId();
        log.info("[headBgImgMediaId] = " +mediaId);
        Map<String, String> resultMap = Maps.newHashMap();
        try {

//            WeixinServiceDL weixinService= objectFactory.getObject();
//            weixinService.reSetConfigStorage(springProfilesActive);
            //PlatformSysInfo platformSysInfoConfig= sysGzhService.getPlatformSysInfo(springProfilesActive);
            //WxMpServiceImpl weixinService = WeixinServiceNew.getWeixinService(platformSysInfoConfig.getSysGzh());

            springProfilesActive=WeixinServiceMap.getReplaceGzh(springProfilesActive);//找替换的 公众号code 20210816

            WeixinServiceDL weixinService= WeixinServiceMap.getWeixinService(springProfilesActive);

            // 获取头像
            File headBgImgFile = weixinService.getMaterialService().mediaDownload(mediaId);
            String fileName = headBgImgFile.getName();
            log.info("[headBgImgFileName] = " + fileName);
            String formatDate = DateUtil.getFormatDate("yyyy-MM-dd", DateUtil.getCurDate());
            String dirName = SysConstant.USER_QRCODE_IMG_OSS_DIR + userId + "/" + formatDate + "/";
            // 上传
            AliyunOssClientUtil.uploadFileByLocalFile(headBgImgFile, dirName + fileName);

            headBgImgUrl = SysConstant.USER_QRCODE_OSS_ACCESS_PREFIX + dirName + fileName;

            resultMap.put("headBgImgUrl", headBgImgUrl);
        } catch (Exception e) {
            e.printStackTrace();
        }
        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setData(resultMap);
        respData.setMsg("成功");
        return respData;
    }

    /**20200513 yl
     * 获取该用户头像地址
     * @param userId
     * @return
     */
    @RequestMapping(value="/getHead", method = RequestMethod.POST)
    public RespData getHead(@RequestHeader("userId") String userId){
        UserInfo userInfo = this.userInfoService.getUserMainInfo(Integer.parseInt(userId));
        // 查询头像路径
        String avatarPath =userInfo.getAvatarUrl();
        Map<String,Object> resultMap = Maps.newHashMap();
        resultMap.put("avatarPath", avatarPath);
        // 获取用户是否关注了公众号
        int concernStatus = Optional.ofNullable(userInfo.getConcernStatus()).orElse(0);
        // 查询会员状态
        int VipStatus = Optional.ofNullable(userInfo.getVipStatus()).orElse(0);
        resultMap.put("concernStatus", concernStatus);
        resultMap.put("VipStatus",VipStatus);
        if (StringUtils.isNotBlank(avatarPath)){
            RespData respData = new RespData();
            respData.setCode(ReturnCode.NORMAL_SUCC);
            respData.setMsg("成功");
            respData.setData(resultMap);
            return respData;
        }
        RespData respData = new RespData();
        respData.setCode(ReturnCode.SERVER_ERROR);
        respData.setMsg("获取失败");
        return respData;
    }

    /**20200513 yl
     * 查询背景
     * @param userId
     * @return
     */
    @RequestMapping(value="/getHeadBgImg", method = RequestMethod.POST)
    public RespData getHeadBgImg(@RequestHeader("userId") String userId,@RequestHeader("identifying") String springProfilesActive){
        HeadBgImgInfo headBgImgInfo = new HeadBgImgInfo();
        headBgImgInfo.setGzhCode(springProfilesActive);
        List<HeadBgImgInfo> headBgImgInfos = this.headBgImgInfoService.selectHeadBgImg(headBgImgInfo);
        if (CollectionUtils.isNotEmpty(headBgImgInfos)){
            RespData respData = new RespData();
            respData.setCode(ReturnCode.NORMAL_SUCC);
            respData.setMsg("成功");
            respData.setData(headBgImgInfos);
            return respData;
        }
        RespData respData = new RespData();
        respData.setCode(ReturnCode.SERVER_ERROR);
        respData.setMsg("获取失败");
        return respData;
    }

    /**20200513 yl
     * 添加背景
     * @param userId
     * @return
     */
    @RequestMapping(value="/addHeadBgImg", method = RequestMethod.POST)
    public RespData addHeadBgImg(@RequestHeader("userId") String userId,@RequestHeader("identifying") String springProfilesActive,@RequestBody HeadBgImgInfo headBgImgInfo){
            headBgImgInfo.setGzhCode(springProfilesActive);
            this.headBgImgInfoService.addHeadBgImg(headBgImgInfo);
            RespData respData = new RespData();
            respData.setCode(ReturnCode.NORMAL_SUCC);
            respData.setMsg("成功");
            return respData;
    }

    /**20200514 yl
     * 合并头像
     * @param userId
     * @param headBgImgInfo
     * @return
     */
    @RequestMapping(value="/makingHeadImg", method = RequestMethod.POST)
    public RespData makingHeadImg(@RequestHeader("userId") String userId,@RequestHeader("identifying") String springProfilesActive,@RequestBody HeadBgImgInfo headBgImgInfo)  {
        // 查询背景图片url
        List<HeadBgImgInfo> headBgImgInfos = this.headBgImgInfoService.selectHeadBgImg(headBgImgInfo);
        if (CollectionUtils.isEmpty(headBgImgInfos)){
            RespData respData = new RespData();
            respData.setCode(ReturnCode.SERVER_ERROR);
            respData.setMsg("获取背景图片失败，请检查");
            return respData;
        }
        String makingHeadUrl = null;
        Map<String, String> resultMap = Maps.newHashMap();
        // 合成头像临时文件
        File ornamentImgFile = null;
        File headUrlImgFile = null;
        File file = null;
        try {

            PlatformSysInfo platformSysInfo= sysGzhService.getPlatformSysInfo(springProfilesActive);
            String wxShareImgPath=platformSysInfo.getWxShareImgPath();

            // 获取背景
            URL httpUrl = new URL(headBgImgInfos.get(0).getBgiImgUrl());
            ornamentImgFile = new File(wxShareImgPath + "result/"+ UUID.randomUUID().toString() +".png");
            FileUtils.copyURLToFile(httpUrl, ornamentImgFile);

            // 获取头像
            String sourceHeadUrl = null;
            if (StringUtils.isBlank(headBgImgInfo.getSourceHeadUrl())){
                // 如果上传的图片url为空 将获取用户头像url
                UserInfo userInfo = this.userInfoService.getUserBaseInfo(Integer.parseInt(userId));
                sourceHeadUrl = userInfo.getAvatarUrl();
            }else {
                sourceHeadUrl =headBgImgInfo.getSourceHeadUrl();
            }
            URL headUrl = new URL(sourceHeadUrl);
            headUrlImgFile = new File(wxShareImgPath + "result/"+ UUID.randomUUID().toString() +".png");
            FileUtils.copyURLToFile(headUrl, headUrlImgFile);
            // 合成图片
            file = SharedImageUtils.generateHeadImage(ornamentImgFile, headBgImgInfos.get(0).getBgiType(), headUrlImgFile,wxShareImgPath);
            String fileName = file.getName();
            String formatDate = DateUtil.getFormatDate("yyyy-MM-dd", DateUtil.getCurDate());
            String dirName = SysConstant.USER_QRCODE_IMG_OSS_DIR + userId + "/" + formatDate + "/";
            // 上传
            AliyunOssClientUtil.uploadFileByLocalFile(file, dirName + fileName);

            makingHeadUrl = SysConstant.USER_QRCODE_OSS_ACCESS_PREFIX + dirName + fileName;

            resultMap.put("makingHeadUrl", makingHeadUrl);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            deleteTemporarilyCachePictures(ornamentImgFile,headUrlImgFile,file);
        }
        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setData(resultMap);
        respData.setMsg("成功");
        return respData;

    }

    /**
     *  删除制作头像生成的临时图片（异步）
     * @param ornamentImgFile
     * @param headUrlImgFile
     * @param makeHeadFile
     */
    @Async
    public void deleteTemporarilyCachePictures(File ornamentImgFile,File headUrlImgFile ,File makeHeadFile){
        if (ornamentImgFile.exists()){
            ornamentImgFile.delete();
        }
        if (headUrlImgFile.exists()){
            headUrlImgFile.delete();
        }
//        if (makeHeadFile.exists()){
//            makeHeadFile.delete();
//        }
    }



}
